package cn.zhoabab.study.seata.storage.service.impl;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.seata.spring.annotation.GlobalTransactional;

import cn.zhoabab.study.seata.storage.dao.StorageMapper;
import cn.zhoabab.study.seata.storage.entity.StorageEntity;
import cn.zhoabab.study.seata.storage.service.StorageService;

@Slf4j
@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    private StorageMapper storageMapper;

    @Override
    @GlobalTransactional
    public Map<String, Object> reduceStock(String code, Long num) {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("success",false);
        StorageEntity storageEntity = storageMapper.selectByCode(code);
        Long remain = storageEntity.getStock() - num;
        storageEntity.setStock(remain);
        storageEntity.setUpdateTime(new Date());
        storageMapper.updateById(storageEntity);
        // 模拟异常
        if (storageEntity.getStock() % 2 == 0) {
            log.error(">>>> 仓库分支事务抛出异常 <<<<");
            throw new RuntimeException("仓库分支事务抛出异常");
        }
        resultMap.put("success",true);
        resultMap.put("message","更新库存成功");
        return resultMap;
    }
}
